package models;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import play.data.validation.Constraints.Required;
import play.db.ebean.Model;

@Entity
public class YouUser extends Model {

	@Required @Id
	public long youId;
	
	@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
	public Set<GoogleToken> linkedAccounts;
	
	public static Model.Finder<Long, YouUser> find = new Finder<Long, YouUser>(
			Long.class, YouUser.class);
	
	public static YouUser create() {
		YouUser	user = new YouUser();
		user.linkedAccounts = new HashSet<GoogleToken>();
		user.save();
		return user;
	}
	
	public boolean addAccount(GoogleToken data) {
		System.out.println(this);
		System.out.println(data);
		boolean added = linkedAccounts.add(data);
		if (added) {
			this.save();
		}
		return added;
	}
	
	public Set<GoogleToken> clearLinks() {
		for (GoogleToken data : linkedAccounts) {
			data.delete();
		}
		linkedAccounts = new HashSet<GoogleToken>();
		this.save();
		
		return linkedAccounts;
	}
	
	public GoogleToken unlink(long linkId) {
		GoogleToken foundData = null;
		for (GoogleToken data : linkedAccounts) {
			if (data.id == linkId) {
				foundData = data;
				data.delete();
				linkedAccounts.remove(data);
				this.save();
				break;
			}
		}
		
		return foundData;
	}
	
	//TODO change this to enable selection of a specific account
	public GCalendarToken getGCalendarToken() {
		GCalendarToken calendarToken = null;
		for (GoogleToken linkData : linkedAccounts) {
			System.out.println(linkData);
			if (linkData instanceof GCalendarToken) {
				calendarToken = (GCalendarToken) linkData;
			}
		}
		return calendarToken;
	}
	
	public static List<YouUser> all(){
		return find.all();
	}

	@Override
	public String toString() {
		return "YouUser [youId=" + youId + ", linkedAccounts=" + linkedAccounts
				+ "]";
	}
	
	public static void emptyBD() {
		List<YouUser> users = find.all();
		for (YouUser youUser : users) {
			youUser.clearLinks();
			youUser.delete();
			youUser.save();
		}
	}

}